<?php
/*
  +----------------------------------------------------------------------+
  | UCModArticlePromotion.php                                                          |
  +----------------------------------------------------------------------+
  | Copyright (c) 2010 snda.com - Web Development Center                 |
  +----------------------------------------------------------------------+
  | Memcache engine                                                      |
  +----------------------------------------------------------------------+
  | Authors: Terry <leo9127@163.com>                                     |
  +----------------------------------------------------------------------+
*/

class UCModArticlePromotion{
	var $yindao; //新手引导开关
	var $yindao_objName = "YINDAO_SWITCH"; //新手引导的COOKIE的KEY
	var $tuiguang; //推广条引导开关
	var $tuiguang_objName = "TUIGUANG_SWITCH"; //推广条的COOKIE的KEY
	var $highest;
	var $highestName = "HIGHEST_PRIORITY"; //最高优先级的COOKIE的KEY
	
	//构造函数，读取COOKIE依据COOKIE的值判断给用户加载的推广条
	function __construct(){
		require_once(dirname(__FILE__).'/../../libraries/UCLibCache.php');
		require_once(dirname(__FILE__).'/../../config/comment/UCConfComment.php');
		require_once(dirname(__FILE__).'/../../libraries/UCLibPDOFactory.php');
		require_once(dirname(__FILE__).'/../user/UCModUserInfo.php');
		require_once(dirname(__FILE__).'/../relation/UCModRelation.php');
		require_once(dirname(__FILE__).'/../store/UCModStore.php');
		$yindao_objName = $_COOKIE[$this->yindao_objName];
		if(empty($yindao_objName)){
			$this->yindao = array();
		}else{
			$yindao_objName = $this->serializationArray($yindao_objName);
			$this->yindao = $yindao_objName;
		}
		$tuiguang_objName = $_COOKIE[$this->tuiguang_objName];
		if(empty($tuiguang_objName)){
			$this->tuiguang = array();
		}else{
			$tuiguang_objName = $this->serializationArray($tuiguang_objName);
			$this->tuiguang = $tuiguang_objName;
		}
		$highest = $_COOKIE[$this->highestName];
		if(empty($highest)){
			$this->highest = array();
		}else{
			$highest = $this->serializationArray($highest);
			$this->highest = $highest;
		}
	}
	
	//写COOKIE
	protected function getCookieInfo($type){
		if($type == '1000'){
			if(is_array($this->yindao) && count($this->yindao)>0){
				$yindao = $this->arraySerialization($this->yindao);
				setcookie($this->yindao_objName,$yindao,time()+3600*24,'/','.sdo.com');
			}
		}
		if($type == '2000'){
			if(is_array($this->tuiguang) && count($this->tuiguang)>0){
				$tuiguang = $this->arraySerialization($this->tuiguang);
				setcookie($this->tuiguang_objName,$tuiguang,time()+3600*24,'/','.sdo.com');
			}
		}
		if($type == '3000'){
			if(is_array($this->highest) && count($this->highest)>0){
				$highest = $this->arraySerialization($this->highest);
				setcookie($this->highestName,$highest,time()+3600*24,'/','.sdo.com');
			}
		}
	}
	
	//将数据序列化为可以供COOKIE存储的数据
	protected function arraySerialization($array){
		if(!is_array($array) || count($array) == 0){
			return false;
		}
		$info = array();
		foreach($array as $key=>$val){
			$info[] = $key.':'.$val;
		}
		$info = implode(",", $info);
		return $info;
	}
	
	//将序列化后的数据转会数组
	protected function serializationArray($obj){
		if(empty($obj)){
			return false;
		}
		$obj = explode(",",$obj);
		if(!is_array($obj) || count($obj) == 0){
			return false;
		}
		$info = array();
		foreach($obj as $key=>$val){
			$tmp = explode(":",$val);
			$info[$tmp[0]] = $tmp[1];
		}
		unset($obj);
		return $info;
	}
	
	//传入变量处理
	protected function escape($data, $data_is_array = false) {
		if ($data_is_array) {
			$tmp = array();
			foreach ($data as $k => $v) {
				$tmp[$k] = htmlspecialchars(html_entity_decode($v,ENT_QUOTES),ENT_QUOTES);
			}
			return $tmp;
		}
		return htmlspecialchars(html_entity_decode($data,ENT_QUOTES),ENT_QUOTES);
  }
  
  //生成MD5的散列KEY
  protected function getNewCid($url,$title,$start_time='',$stop_time=''){
		list($usec, $sec) = explode(" ", microtime());
		$time = ((float)$usec + (float)$sec);
		$rand = rand(0,9500);
		return  md5($url.$title.$start_time.$stop_time.$time.$rand);
	}
	
	//生成KEY
	protected function _getMemcacheKey($channel_id='',$user=''){
		if(empty($channel_id) && empty($user)){
			return false;
		}
		if(!empty($channel_id) && empty($user)){
			return md5('ArticlePromotion_channel_'.$channel_id);
		}else if(empty($channel_id) && !empty($user)){
			return md5('ArticlePromotion_userid_'.$channel_id);
		}else if(!empty($channel_id) && !empty($user)){
			return md5('ArticlePromotion_userid_'.$channel_id);
		}else{
			return false;
		}
	}
	
	//将数据写入DB
	public function insertSpread($data,$file=''){
		if (!$data['ar_show_url'] || !$data['ar_url'] || !$data['channel_id'] || !$data['son_channel']){
  		trigger_error("Wrong Input!\n");
			return false;
  	}
  	if($data['channel_id'] != '1000'){
  		if(!$data['start_time']){
  			$data['start_time'] = date('Y-m-d H:i:s');
  		}
  		if(!$data['stop_time']){
  			$data['stop_time'] = date('Y-m-d H:i:s',(time()+(60*60*24*365)));
  		}
  	}else{
  		$data['start_time'] = '';
  		$data['stop_time'] = '';
  	}
  		
  	//判断是否是合法的图片或FLASH
  	$extend = pathinfo($data['ar_show_url']);
  	$extend = strtolower($extend["extension"]);
  	$extension = array('jpg','JPG','gif','GIF','png','PNG','swf','SWF');
  	if(!in_array($extend,$extension)){
  		return false;
  	}
  	if($extend == 'swf' || $extend == 'SWF'){
  		$data['show_type'] = 1;
  	}else{
  		$data['show_type'] = 0;
  	}
  	$data['submit_time'] = date("Y-m-d");
   	//将数据写入DB
  	if(!$data['ar_id']){
  		$data['ar_id'] = $this->getNewCid($data['ar_show_url'],$data['title'],$data['start_time'],$data['stop_time']);
  		$pdo = UCLibPDOFactory::getPDO('spread','','commentdbconfig');
  		if(!$pdo->insert($data)){
  			return false;
  		}
  	}else{
  		$pdo = UCLibPDOFactory::getPDO('spread','','commentdbconfig');
  		if(!$pdo->update($data,array('ar_id'=>$data['ar_id']))){
  			return false;
  		}
  	}
  	if($data['channel_id'] == 2000 && $data['son_channel'] == 2002){
  		 //将用户名单写入DB
  		 $this->setUserList($data['ar_id'],$file);
  	}
  	//更新缓存
  	$key = $this->_getMemcacheKey($data['channel_id']);
  	$cache = new UCLibCache('spread');
  	$cache->delete($key);
  	$cache->close();
   	return $data['ar_id'];
	}
	
	//读取推广条数据
	public function getSpread($channel_id){
		$key = $this->_getMemcacheKey($channel_id);
		$cache = new UCLibCache('spread');
		$row = $cache->read($key);
		if($row == false && $row != 'error'){
			$pdo = UCLibPDOFactory::getPDO('spread','','commentdbconfig');
			if($channel_id == 1000){
				$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE channel_id=?";
				$params = array($channel_id);
			}else{
				$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE channel_id=? and stop_time>?";
				$params = array($channel_id,date("Y-m-d H:i:s"));
			}
			$ret = $pdo->query_with_prepare($sql,$params);
			if($ret == false || !is_array($ret)){
				$cache->write($key,'error',1800);
  			$cache->close();
  			return false;
  		}
  		$row = $ret;
  		$cache->write($key,$row);
  		$cache->close();
  	}
  	if($row == 'error'){
  		return false;
  	}else{
  		return $row;
  	}
	}
	
	//将用户名单写入DB
	public function setUserList($ar_id,$file){
		$handle = fopen($file, "rb");
		while(!feof($handle)){
			$buffer = fgets($handle, 128);
			$buffer = strtolower(trim($buffer));
			$pdo = UCLibPDOFactory::getPDO('spreaduser',$buffer,'commentdbconfig');
			$sql = "SELECT count(*) as tatal FROM $pdo->database.$pdo->table WHERE ar_id=? and user_id=?";
			$data = array('ar_id'=>$ar_id,'user_id'=>$buffer);
			$tatal = $pdo->query_one_row_with_prepare($sql,$params);
			if($tatal == 0){
				$pdo->insert($data);
				$key = md5("getUserSpread_".$buffer."_2002");
				$cache = new UCLibCache('spread');
				$cache->delete($key);
				$cache->close();
			}
		}
		fclose($handle);
	}
	
	//新手引导应该显示的推广条
	public function newsGuide($user,$swf=true){
		$user = strtolower(trim($user));
		//判断新手推广条开关是否设置
		if(is_array($this->yindao) && count($this->yindao)>0){
			$num = 0;
			foreach($this->yindao as $key=>$val){
				if($val == 'ON') $num++;
			}
			if($num == 0){
				//将用户不需要读取新手引导推广条的值记入CACHE
				//$this->setGuideType($user);
				return false;
			}
		}
		//判断用户是否设置了头像
		$uinfo = UCModUserInfo::getUser($user);
		if(empty($this->yindao['1001']) || $this->yindao['1001'] == 'ON'){
			$data = $uinfo->getAttributes(array(USERINFO_AVATAR_VERSION));
			if($data[USERINFO_AVATAR_VERSION] == 0){
				$this->yindao['1001'] = 'ON';
			}else{
				$this->yindao['1001'] = 'OFF';
			}
		}
		//判断用户基本资料是否大于40%是否设置
		if(empty($this->yindao['1002']) || $this->yindao['1002'] == 'ON'){
			$data = $uinfo->getCompletePercent(USERINFO_COMPLETE_BASIC);
			if($data <= 40){
				$this->yindao['1002'] = 'ON';
			}else{
				$this->yindao['1002'] = 'OFF';
			}
		}
		//判断用户是否有好友数是否大于5个
		if(empty($this->yindao['1003']) || $this->yindao['1003'] == 'ON'){
			$obj = new UCModRelation($user);
	  	$data = $obj->getRelationFollowCount();
	  	if($data <= 5){
	  		$this->yindao['1003'] = 'ON';
	  	}else{
	  		$this->yindao['1003'] = 'OFF';
	  	}
	  }
	  //判断用户是否有小应用
	  if(empty($this->yindao['1004']) || $this->yindao['1004'] == 'ON'){
	  	$data = UCModStore::getInstance()->getRecentUser($user,1);
	  	if(count($data) == 0){
	  		$this->yindao['1004'] = 'ON';
	  	}else{
	  		$this->yindao['1004'] = 'OFF';
	  	}
	  }
	  //写COOKIE
	  $this->getCookieInfo(1000);
  	$switch = false;
  	foreach($this->yindao as $newk=>$newv){
  		if($newv == 'ON'){
  			$switch[] = array('key'=>$newk,'val'=>$newv);//记录所有状态是打开的推广条
  		}
  	}
	  if($switch === false){
	  	//将用户不需要读取新手引导推广条的值记入CACHE
			//$this->setGuideType($user);
	  	return false;
	  }
	  //读取推广条数据
	  $row = $this->getSpread(1000);
		if($row == false || !is_array($row)){
			return false;
		}
		//如果用户浏览器不支持FLASH则去除FLASH的推广条
		if($swf != true){
			foreach($row as $key=>$val){
				if($val['show_type'] == 1) unset($row[$key]);
			}
		}
		if($row == false || count($row) == 0){
			return false;
		}
		//新建一个ARRAY来记录候选的推广条
		$newSpread = array();
		foreach($switch as $skey=>$sval){
			foreach($row as $rokey=>$roval){
				if($roval['son_channel'] == $sval['key']) $newSpread[$sval['key']][] = $roval;
			}
		}
		$ns = false;
		if(is_array($newSpread['1001']) && $ns == false){
			$ns = $newSpread['1001'];
		}
		if(is_array($newSpread['1002']) && $ns == false){
			$ns = $newSpread['1002'];
		}
		if(is_array($newSpread['1003']) && $ns == false){
			$ns = $newSpread['1003'];
		}
		if(is_array($newSpread['1004']) && $ns == false){
			$ns = $newSpread['1004'];
		}
		$num = rand(0,(count($ns)-1));
		return $ns[$num];
	}
	
	//若用户不需要读取新手引导推广条则在CACHE中记录一个值,记录一个小时
	public function setGuideType($user){
		$user = strtolower(trim($user));
		$key = md5('newsGuideType_fengchen9127_'.$user);
		$cache = new UCLibCache('spread');
		$cache->write($key,true,3600);
  	$cache->close();
  }
  
  //读取用户是否需要新手引导推广条
	public function getGuideType($user){
		$user = strtolower(trim($user));
		$key = md5('newsGuideType_fengchen9127_'.$user);
		$cache = new UCLibCache('spread');
		$row = $cache->read($key);
		$cache->close();
		return $row;
	}
	
	//读取用户对应的推广条
	public function getUserSpread($user,$ar_id){
		$user = strtolower(trim($user));
		$ar_id = strtolower(trim($ar_id));
		$key = md5("getUserSpread_".$user."_2002");
		$cache = new UCLibCache('spread');
		$row = $cache->read($key);
		if($row == false && $row != 'error'){
			$pdo = UCLibPDOFactory::getPDO('spreaduser',$user,'commentdbconfig');
			$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE ar_id=? and user_id=?";
			$params = array($ar_id,$user);
			$ret = $pdo->query_with_prepare($sql,$params);
			if($ret == false || !is_array($ret)){
				$cache->write($key,'error');
  			$cache->close();
  			return false;
  		}
  		$row = $ret;
  		$cache->write($key,$row);
  	}
  	if($row == 'error'){
  		return false;
  	}
  	$cache->close();
  	$info = false;
  	foreach($row as $keys=>$val){
  		if($val['ar_id'] == $ar_id){
  			$info = true;
  			break;
  		}
  	}
  	return $info;
	}
	
	//读取推广数据
	public function getSpreadInfo($user,$swf=true){
		$user = strtolower(trim($user));
		//判断用户打开和关闭的对应推广条
		if(empty($this->tuiguang['2001'])){
			$this->tuiguang['2001'] = 'ON';
		}
		if(empty($this->tuiguang['2002'])){
			$this->tuiguang['2002'] = 'ON';
		}
		if(empty($this->tuiguang['2003'])){
			$this->tuiguang['2003'] = 'ON';
		}
		if(empty($this->tuiguang['2004'])){
			$this->tuiguang['2004'] = 'ON';
		}
		//写COOKIE
	  $this->getCookieInfo(2000);
		$switch = false;
		foreach($this->tuiguang as $newk=>$newv){
			if($newv == 'ON'){
				$switch[] = array('key'=>$newk,'val'=>$newv);//记录所有状态是打开的推广条
	  	}
	  }
	  if($switch === false){
  		return false;
  	}
  	$row = $this->getSpread(2000);
 		if($row == false){
			return false;
		}
		if($swf != true){
			foreach($row as $key=>$val){
				if($val['show_type'] == 1) unset($row[$key]);
			}
		}
		if(count($row) == 0){
			return false;
		}
		//新建一个ARRAY来记录候选的推广条
		$newSpread = array();
		foreach($switch as $skey=>$sval){
			foreach($row as $rokey=>$roval){
				if($roval['son_channel'] == $sval['key']) $newSpread[$sval['key']][] = $roval;
			}
		}
		$datatype = array();
		//读取全局推广条
		if(is_array($newSpread['2001']) && count($newSpread['2001'])>0){
			foreach($newSpread['2001'] as $key=>$val){
				if($val['start_time']<=date("Y-m-d H:i:s") && $val['stop_time']>=date("Y-m-d H:i:s"))	$datatype[] = $val;
			}
		}
		//读取名单推广条
		if(is_array($newSpread['2002']) && count($newSpread['2002'])>0){
			foreach($newSpread['2002'] as $key=>$val){
				if($val['start_time']<=date("Y-m-d H:i:s") && $val['stop_time']>=date("Y-m-d H:i:s")){
					//读取用户名单是否对应该推广条
					$user_info = $this->getUserSpread($user,$val['ar_id']);
					if($user_info == true){
						$datatype[] = $val;
					}
				}
			}
		}
		//有无消费记录
		/*********等待开发*********/
		//是否资深活跃用户
		/*********等待开发*********/
		$total = count($datatype);
		if($total == 0){
			return false;
		}else{
			$rand = rand(0,($total-1));
			return $datatype[$rand];
		}
	}
	
	//读取最高优先级数据
	public function highestPriority($user,$swf=true){
		$user = strtolower(trim($user));
		$row = $this->getSpread(3000);
		if($row === false || !is_array($row)){
			return false;
		}
		//如果用户浏览器不支持SWF排除SWF的推广条
		if($swf != true){
			foreach($row as $key=>$val){
				if($val['show_type'] == 1) unset($row[$key]);
			}
		}
		if($row === false || count($row) == 0){
			return false;
		}
		//排除还未开始的推广条
		foreach($row as $key=>$val){
			if($val['start_time'] > date("Y-m-d H:i:s")) unset($row[$key]);
		}
		if($row === false || count($row) == 0){
			return false;
		}
		//排除已经结束的推广条
		foreach($row as $key=>$val){
			if($val['stop_time'] < date("Y-m-d H:i:s")) unset($row[$key]);
		}
		if($row === false || count($row) == 0){
			return false;
		}
		if(empty($this->highest)){
			foreach($row as $key=>$val){
				if($val['son_channel'] == '3001'){
					$this->highest[$val['ar_id']] = 'ON';
				}elseif($val['son_channel'] == '3002'){
					//读取用户名单是否对应该推广条
					$user_info = $this->getUserSpread($user,$val['ar_id']);
					if($user_info === true){
						$this->highest[$val['ar_id']] = 'ON';
					}
				}
			}
		}else{
			foreach($row as $key=>$val){
				if(empty($this->highest[$val['ar_id']])) $this->highest[$val['ar_id']] = 'ON';
			}
		}
		$this->getCookieInfo(3000);
		$new = array();
		foreach($this->highest as $key=>$val){
			if($val == 'ON'){
				foreach($row as $rkey=>$rval){
					if($rval['ar_id'] == $key) $new[] = $rval;
				}
			}
		}
		$total = count($new);
		if($total == 0){
			return false;
		}else{
			$rand = rand(0,($total-1));
			return $new[$rand];
		}
	}
				
	
	//依据传入的用户名返回用户当前应该显示的推广条
	public function currentSpread($user,$swf=true){
		$user = strtolower(trim($user));
		//首先读取最高优先级的推广条
		$row = $this->highestPriority($user,$swf);
		if($row != false && is_array($row)){
			return $row;
		}
		$row = $this->newsGuide($user,$swf);
		if($row != false && is_array($row)){
			return $row;
		}else{
			$row = $this->getSpreadInfo($user,$swf);
			return $row;
		}
	}
	
	//直接重DB读取推广条数据供管理使用
	public function dbListSpread($channel_id=''){
		$data = array();
		$pdo = UCLibPDOFactory::getPDO('spread','','commentdbconfig');
		$sql = "SELECT * FROM $pdo->database.$pdo->table";
		if(!empty($channel_id)){
			$sql .=" WHERE channel_id=?";
			$data[] = $channel_id;
		}
		$sql .= ' ORDER BY submit_time DESC';
		$ret = $pdo->query_with_prepare($sql,$data);
		if($ret == false || !is_array($ret)){
 			return false;
 		}
 		return $ret;
	}
	
	//读取单条推广条数据
	public function getOneSpread($ar_id){
		$pdo = UCLibPDOFactory::getPDO('spread','','commentdbconfig');
		$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE ar_id=?";
		$data = array($ar_id);
		$ret = $pdo->query_one_row_with_prepare($sql,$data);
		if($ret === false || count($ret) == 0){
			return false;
		}
		return $ret;
	}
	
	//删除推广条
	public function delSpread($ar_id){
		//读取推广条数据
		$data = $this->getOneSpread($ar_id);
		//删除数据
		$pdo = UCLibPDOFactory::getPDO('spread','','commentdbconfig');
		$sql = "DELETE FROM $pdo->database.$pdo->table WHERE ar_id=?";
		$data = array($ar_id);
		$row = $pdo->exec_with_prepare($sql,$data);
		//更新缓存
  	$key = $this->_getMemcacheKey($data['channel_id']);
		$cache = new UCLibCache('spread');
		$cache->delete($key);
		$cache->close();
		return true;
	}
   		
}
?>